//SYSC3303-assignment#1
//Student Name: Qi Zhang
//Student No. 100839438
//Date:12,July,2011

import java.io.*;
import java.net.*;


public class Server {

   DatagramPacket sendPacket, receivePacket;
   DatagramSocket sendSocket, receiveSocket;

   public Server()
   {
      try {
         // Construct a datagram socket and bind it to 69
         // port on the local host machine. This socket will be used to
         // receive UDP Datagram packets.
    	  sendSocket= new DatagramSocket();
         receiveSocket = new DatagramSocket(69);
         
      } catch (SocketException se) {
         se.printStackTrace();
         System.exit(1);
      }
   }

   public void receiveAndEcho()
   {
      // Construct a DatagramPacket for receiving packets up 
      // to 17 bytes long (the length of the byte array).
      byte []data=new byte[16];
      receivePacket=new DatagramPacket(data,data.length);
      
      while(1<3){ 
      // Block until a datagram packet is received from receiveSocket.
      try {         
         receiveSocket.receive(receivePacket);
      } catch (IOException e) {
         e.printStackTrace();
         System.exit(1);
      }

      // Process the received datagram.
      System.out.println("Server: Packet received:");
      data = receivePacket.getData(); 
      System.out.println("Containing: (Bytes)" +data);
      String s=new String(data);
      System.out.println("Server: Containing:(String)"+ s);
 
    //analyze the request
      byte []msg=new byte[4];
      if(data[1]==1){
    	  msg[0]=0;
    	  msg[1]=3;
    	  msg[2]=0;
    	  msg[3]=1;
      }
      else if(data[1]==2){
    	  msg[0]=0;
    	  msg[1]=4;
    	  msg[2]=0;
    	  msg[3]=0;
      }else{
    	  msg[0]=0;
    	  msg[1]=5;
      }
      
      //Send response 
      
      try {
          sendPacket = new DatagramPacket(msg, msg.length,
                                        InetAddress.getLocalHost(), 68);
       } catch (UnknownHostException e) {
          e.printStackTrace();
          System.exit(1);
       }
       try {
           sendSocket.send(sendPacket);
        } catch (IOException e) {
           e.printStackTrace();
           System.exit(1);
        }

      System.out.println("Server: response sent");
      System.out.println("-------------------------");
      }
      // We're finished, so close the sockets.
      //sendSocket.close();
      //receiveSocket.close();
      
   }

   public static void main( String args[] )
   {
      Server c = new Server();
      c.receiveAndEcho();
   }
}
